package guowei.guliorder.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import guowei.guliorder.order.config.AlipayTemplate;
import guowei.guliorder.order.service.OrderService;
import guowei.guliorder.order.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 接收支付宝完成支付成功后发送的异步请求  只有返回success 支付宝才会停止发送此请求
 */
@RestController
public class AlipayListener {

    @Autowired
    AlipayTemplate alipayTemplate;
    @Autowired
    OrderService orderService;

    @PostMapping("/order/alipay")
    public String listenAlipay(PayAsyncVo payAsyncVo,HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {

        System.out.println("接收到支付宝支付返回结果的参数为: "+payAsyncVo);
        //处理支付宝的支付结果    修改订单流水和 订单状态之前首先要验签

        //获取支付宝POST过来反馈信息       只有是支付宝发来的信息才能接下来的操作
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

//  调用这个方法 若签名验证成功 才能接着调用业务逻辑
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

        if (signVerified){
            System.out.println("签名验证成功");
            String val = orderService.dealWithAliPay(payAsyncVo);
            return val;
        }else {
            System.out.println("签名验证失败");
            return "error";
        }



    }
}
